package com.funmi.lizip.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.common.exception.ApplicationException;
import com.funmi.lizip.entity.PatrolTrack;
import com.funmi.lizip.entity.Personnel;
import com.funmi.lizip.entity.User;
import com.funmi.lizip.entity.dto.personnel.PersonnelAddRequest;
import com.funmi.lizip.entity.dto.personnel.PersonnelQueryRequest;
import com.funmi.lizip.entity.dto.personnel.PersonnelUpdateRequest;
import com.funmi.lizip.entity.enums.PathEnum;
import com.funmi.lizip.entity.vo.PersonnelVo;
import com.funmi.lizip.entity.vo.UserInfoVo;
import com.funmi.lizip.security.entity.SecurityUser;
import com.funmi.lizip.service.PatrolTrackService;
import com.funmi.lizip.service.PersonnelService;
import com.funmi.lizip.service.UserService;
import com.funmi.lizip.utils.MyJsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yeyg
 * @since 2022-11-03
 */
@Api(tags = "巡护人员模块")
@RestController
@RequestMapping("/personnel")
public class PersonnelController {

    @Autowired
    private PersonnelService personnelService;
    @Autowired
    @Lazy
    private UserService userService;
    @Autowired
    @Lazy
    private PatrolTrackService patrolTrackService;

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "巡护人员详细信息")
    @GetMapping("/{id}")
    public R get(@PathVariable int id) {
        Personnel personnel = personnelService.getById(id);
        if (ObjectUtils.isEmpty(personnel)){
            return R.success().message("无数据或被删除");
        }
        if (ObjectUtils.isEmpty(personnel.getPosition())){
            String s = "{}";
            personnel.setPosition(new JSONArray(JSONArray.parseArray(s)));
        }
        if (ObjectUtils.isEmpty(personnel.getPositionJson())){
            String s = "{}";
            personnel.setPositionJson(new JSONObject(JSONObject.parseObject(s)));
        }
        if (ObjectUtils.isEmpty(personnel.getPhoto()) || personnel.getPhoto().equals("")){
            personnel.setPhoto("PersonnelPhoto" + "/" + "defaultPhoto.jpg");
        }
        return R.success().data(personnel);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "分页获取巡护人员信息")
    @GetMapping("")
    public R getList(PersonnelQueryRequest request) throws IllegalAccessException {
        long current = 1;
        long size = 10;
        PersonnelQueryRequest personnelQueryRequest = MyJsonUtil.setNullValue(request);
        Personnel personnelQuery = new Personnel();
        if (request != null) {
            BeanUtils.copyProperties(personnelQueryRequest, personnelQuery);
            current = request.getPage();
            size = request.getPageSize();
        }
        personnelQuery.setName(null);
        QueryWrapper<Personnel> queryWrapper = new QueryWrapper<>(personnelQuery);
        if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getName())){
            queryWrapper.like("name",request.getName());
        }
        Page<Personnel> personnelPage = personnelService.page(new Page<>(current, size), queryWrapper);

        PageDTO<PersonnelVo> personnelVoPage = new PageDTO<>(personnelPage.getCurrent(), personnelPage.getSize(), personnelPage.getTotal());
        List<PersonnelVo> personnelVoList = personnelPage.getRecords().stream().map(personnel -> {
            PersonnelVo personnelVo = new PersonnelVo();
            BeanUtils.copyProperties(personnel, personnelVo);
            if (ObjectUtils.isEmpty(personnelVo.getPosition())){
                personnelVo.setPosition(new JSONArray());
            }
            // 设置最近的上线时间
            String contactTel = personnel.getContactTel();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("username", contactTel);
            User one = userService.getOne(userQueryWrapper);
            if (!ObjectUtils.isEmpty(one)){
                personnelVo.setLoginAt(one.getLoginAt());
            }else {
                personnelVo.setLoginAt(null);
            }
            return personnelVo;
        }).collect(Collectors.toList());
        personnelVoPage.setRecords(personnelVoList);
        return R.success().data(personnelVoPage);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改巡护人员参数示例")
    @PutMapping("/testUpdate")
    public R updateEX(@RequestBody PersonnelUpdateRequest request) {
        return R.success();
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "新增巡护人员参数示例")
    @PostMapping("/testAdd")
    public R addEX(@RequestBody PersonnelAddRequest request) {
        return R.success();
    }


    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改巡护人员信息")
    @PutMapping("")
    public R update(@RequestBody HashMap<String, Object> request) {
        boolean b = personnelService.updateByID(request);
        if (b) {
            return R.success().message("修改成功");
        }
        return R.fail().message("修改失败");
    }


    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "删除巡护人员")
    @DeleteMapping("/{id}")
    public R delete(@PathVariable int id) {
        boolean b = personnelService.deleteByID(id);
        if (b) {
            return R.success().message("删除成功");
        }
        return R.success().message("删除失败");
    }

    private Boolean a = false;

    @Transactional(rollbackFor = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "新增巡护人员")
    @PostMapping("")
    public R add(@RequestBody HashMap<String, Object> request) throws IOException {
        if (request == null) {
            return R.success().data("数据为空");
        }

        Personnel personnel = JSONObject.parseObject(JSONObject.toJSONBytes(request), Personnel.class);
        List<Personnel> list = personnelService.list();
        list.forEach(name -> {
            if (personnel.getContactTel().equals(name.getContactTel())){
                a = true;
            }
        });
        if (a){
            return R.fail().message("手机号已经被注册");
        }

        // Personnel personnel = JSONObject.parseObject(JSONObject.toJSONBytes(request), Personnel.class);

        /*if (request.get("otherMsg") != null && request.get("otherMsg") != "") {
            personnel.setOtherMsg(new JSONObject((Map<String, Object>) request.get("otherMsg")));
        }*/
        if (request.get("position") != null && request.get("position") != "") {
            personnel.setPosition(new JSONArray((List<Object>) request.get("position")));
        }
        if (request.get("positionJson") != null && request.get("positionJson") != "") {
            personnel.setPositionJson(new JSONObject((Map<String, Object>) request.get("positionJson")));
        }
        File dest = new File(PathEnum.PATH.getText() +"\\"+"PersonnelPhoto"+"\\"+personnel.getContactTel()+"\\"+ personnel.getPhoto());
        // 将暂存的图片移动到指定文件夹中
        // 文件夹名称
        Path directories = Files.createDirectories(dest.getParentFile().toPath());
        File startFile = new File(PathEnum.PATH.getText() +"\\"+ personnel.getPhoto());
        boolean b = startFile.renameTo(dest);
        if (!b){
            R.fail().message("图片保存失败");
        }
        personnel.setPhoto(personnel.getContactTel()+"\\"+ personnel.getPhoto());

        personnel.setDelete(false);
        personnel.setCreateAt(LocalDateTime.now());

        boolean save = personnelService.savePersonAndUser(personnel);
        // 同时增加一个user护林员账号，默认密码，并且以联系方式·contact_tel·为账号名称

        if (save) {
            return R.success().message("新增成功");
        }
        return R.success().message("新增失败");
    }


    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改巡护人员位置")
    @PutMapping("/{latitude}/{longitude}")
    public R update(@PathVariable String latitude, @PathVariable String longitude) {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Object principal = authentication.getPrincipal();
        QueryWrapper<Personnel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contact_tel", principal.toString());
        Personnel one = personnelService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)){
            throw new ApplicationException("定位失败");
        }
        String s = "[" + longitude + ", " + latitude + "]";
        JSONArray position = JSONArray.parseArray(s);
        one.setPosition(position);
        // 判断是否正在巡护, 没有则不修改轨迹2
        //patrolTrackService
        // 定位之后, 存储定位坐标到轨迹
        boolean b1 = patrolTrackService.savePatrolTrack(latitude, longitude);


        boolean b = personnelService.updateById(one);
        if (b){
            return R.success().data("定位成功");
        }
        return R.fail().data("定位失败");
    }


    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "根据护林员id 获取巡护轨迹列表")
    @GetMapping("/attendance/{id}")
    public R getAttendance(@PathVariable int id) {
        List<PatrolTrack> patrolTracks = personnelService.getAttendance(id);
        return R.success().data(patrolTracks);
    }







}

